package com.monkeyboy.service;

import com.monkeyboy.common.exception.GlobalException;
import com.monkeyboy.dao.BaseDao;
import com.monkeyboy.framework.RedisCache;
import com.monkeyboy.model.LoginBody;
import com.monkeyboy.model.SysUser;
import com.monkeyboy.security.LoginUser;
import com.monkeyboy.security.service.TokenService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;

/**
 * @Author Gavin
 * @date 2020.07.06 13:09
 */
@Service
@Slf4j
public class UserService {
    @Autowired
    private TokenService tokenService;

    @Resource
    private AuthenticationManager authenticationManager;

    @Autowired
    private RedisCache redisCache;
    @Autowired
    private BaseDao bd;

    public String login(LoginBody loginBody) throws Exception {
        //这儿可以进行对验证码验证
        if (!"123456".equals(loginBody.getUuid())) {
            throw new GlobalException("验证码错误。");
        }
        // 开始调用springsecurity进行身份验证，返回一个授权的认证对象authentication
        Authentication authentication = null;
        try {
            // 该方法会去调用UserDetailsServiceImpl.loadUserByUsername
            authentication = authenticationManager
                    .authenticate(new UsernamePasswordAuthenticationToken(loginBody.getUsername(), loginBody.getPassword()));
        } catch (Exception e) {
            if (e instanceof BadCredentialsException) {
                log.warn("用户名/密码不匹配");
                throw new GlobalException("用户名/密码不匹配");
            } else {
                throw new GlobalException(e.getMessage());
            }
        }
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        return tokenService.createToken(loginUser);
    }

    public ArrayList<SysUser> getAllUser() throws Exception {
        ArrayList<SysUser> userList = (ArrayList<SysUser>) bd.findForList("UserMapper.getAllUser", null);
        return userList;
    }
}
